package com.css.apps.base.sysjob.action;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.css.apps.base.role.model.SRole;
import com.css.apps.base.sysjob.model.SysJob;
import com.css.db.query.QueryCache;
import com.css.util.ListUtil;
import com.css.util.Messages;
import com.css.util.StringHelper;
import com.css.webbase.webwork.action.AdminAction;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionContext;

public class DirOrgJobSysRoles extends AdminAction{
	private static final long serialVersionUID = -6145558062732651201L;
	private static Log log = LogFactory.getLog(DirOrgJobSysRoles.class);
	private String orgId;
	private String jobId;
	
	
	@SuppressWarnings("unchecked")
	@Override
	protected String adminGo() {
		if (StringHelper.isEmpty(orgId) || StringHelper.isEmpty(jobId)) {
			return Action.SUCCESS;
		}
		try {
			Map<String, List<SRole>> map = new LinkedHashMap<String, List<SRole>>();
			List<SRole> list = null;
			QueryCache qc = new QueryCache("select a.uuid from SysJob a "+ getWhere() + "order by a.sysId");
			setWhere(qc);
			QueryCache querySysIds = new QueryCache("select distinct a.sysId from SysJob a "+ getWhere() + "order by a.sysId");
			setWhere(querySysIds);
			List<String> SysIds = querySysIds.list();
			List<String> sysJobIds = qc.list();
			List<SysJob> sysJobs = QueryCache.idToObj(SysJob.class, sysJobIds);
			if (!ListUtil.isLstEmpty(SysIds)) {
				for (int i = 0; i < SysIds.size(); i++) {
					list = new ArrayList<>();
					for (SysJob sysJob : sysJobs) {
						if (SysIds.get(i).equals(sysJob.getSysId())) {
							SRole role = QueryCache.get(SRole.class, sysJob.getRoleId());
							list.add(role);
						}
					}
					map.put(SysIds.get(i), list);
				}
			}
			ActionContext.getContext().put("selectSys", map);
			return Action.SUCCESS;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			setMessage(Messages.getString("systemMsg.exception"));
			return Action.ERROR;
		}
	}
	
	public String getWhere() {
		StringBuffer sb = new StringBuffer("where 1=1 ");
		if (StringHelper.isNotEmpty(orgId)) {
			sb.append(" and a.orgId =:orgId ");
		}
		if (StringHelper.isNotEmpty(jobId)) {
			sb.append(" and a.jobId =:jobId ");
		}
		return sb.toString();
	}
	
	public void setWhere(QueryCache qc) {
		if (StringHelper.isNotEmpty(orgId)) {
			qc.setParameter("orgId", orgId);
		}
		if (StringHelper.isNotEmpty(jobId)) {
			qc.setParameter("jobId", jobId);
		}
	}
	
	public String getOrgId() {
		return orgId;
	}

	public void setOrgId(String orgId) {
		this.orgId = orgId;
	}

	public String getJobId() {
		return jobId;
	}

	public void setJobId(String jobId) {
		this.jobId = jobId;
	}
}